#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os,sys,socket
from time import sleep
dir = os.path.dirname
root_path = dir(dir(os.path.realpath(__file__)))
sys.path.append(root_path)
from common.a_env_PATH import pathConf
from common.j_emailDemo import SendMail,Robot
from common.c_public import pathConf,openReade,getStrLines


class RunTest():
    def __init__(self):
        self.find_reportTime = 0               # 初始化生成报告计时，累加等待报告生成时间


    def find_report(self,sendMailTime,overTime=10):
        """
        查找最新报告文件
        :overTime : 默认超时时间10秒
        :return : True
        """
        try:
            reportTime = os.path.getmtime(pathConf.get_reportPath())
            # print("文件存在")
            print("报告时间：",reportTime)
            if round(reportTime) > round(sendMailTime):
                # print("sendMailTime 初始化时间小于报告生成时间：")
                # sleep(1)
                return True
            else:
                sleep(1)
                self.find_reportTime += 1
                if self.find_reportTime <= overTime:
                    self.find_report(sendMailTime=sendMailTime)
                else:
                    return False
        except (NameError, FileNotFoundError):
            # print("文件不存在")
            sleep(1)
            self.find_reportTime += 1
            if self.find_reportTime <= overTime:
                self.find_report(sendMailTime=sendMailTime)
            else:
                return False


    def StartRun(self):
        platName = sys.platform
        runTimestamp = SendMail.timestamp
        print("运行时间：",runTimestamp)
        if platName.startswith("win"):
            if socket.gethostname() != "yu1130" or True:
                os.system('chcp 65001')
                # command = r"pytest --html=%s --self-contained-html " % pathConf.get_reportPath()
                # command = r"pytest --html=%s --self-contained-html > %s" % (pathConf.get_reportPath(),pathConf.get_reportLog())
                command = r"pytest --html=%s --self-contained-html > %s" % (pathConf.get_reportPath(), pathConf.get_reportLog())
                os.system(command)
                if self.find_report(runTimestamp):
                    SendMail.add_file(pathConf.get_reportPath())
                    SendMail.send()
                    Rob = Robot()
                    Rob.send_report()
                    Rob.send_reportLog()
                    # Rob.send_message(message=SendMail.runtime + "-测试报告")
                    log = openReade(pathConf.get_reportLog())
                    logline = getStrLines(log, ":uri")
                    if len(logline) > 4:
                        Rob.send_message(message="以下接口存在异常，请关注：" + "\n" + logline)
                        print("发生告警消息完成")
                    else:
                        Rob.send_message(message=SendMail.runtime + "-测试报告")
                        print("发生报告消息完成")
            else:
                command = r"pytest --html=%s --self-contained-html " % pathConf.get_reportPath()
                os.system(command)
                if self.find_report(runTimestamp):
                    SendMail.add_file(pathConf.get_reportPath())
                    SendMail.send()

        elif platName.startswith("linux"):
            # print("Linux平台名称：", platName)
            # print("项目根目录：",pathConf.top_path)
            # print("报告目录：", pathConf.get_reportPath())
            command = r"pytest --html=%s --self-contained-html > %s" % (pathConf.get_reportPath(), pathConf.get_reportLog())
            os.system(command)
            if self.find_report(runTimestamp):
                SendMail.add_file(pathConf.get_reportPath())
                SendMail.send()
                Rob = Robot()
                Rob.send_report()
                Rob.send_reportLog()
                log = openReade(pathConf.get_reportLog())
                logline = getStrLines(log,":uri")
                if len(logline) > 4:
                    Rob.send_message(message="以下接口存在异常，请关注：" + "\n" + logline)
                    print("发生告警消息完成")
                else:
                    Rob.send_message(message=SendMail.runtime + "-测试报告")
                    print("发生报告消息完成")
RunTestC = RunTest()
RunTestC.StartRun()
if __name__ == "__main__":
    pass
    # RunTestC = RunTest()
    # RunTestC.StartRun()
    # print(root_path)
